<template>
  <el-container class="page-container" style="height: 100vh;">
    <!-- 顶部标题和横排按钮区域 -->
    <el-header class="top-section">
      <span class="title">智能安防社区系统</span>
      <el-row class="button-row" type="flex" justify="end" align="middle" style="margin-top: -10px;"> <!-- 使用负上边距可能不是最佳实践，这里仅作为示例 -->
        <el-col :span="30" class="top-button-row">
          <el-button type="primary" class="button-margin">大屏展示</el-button>
          <el-button type="primary" class="button-margin">社区管理</el-button>
          <el-button type="primary" class="button-margin">视频监控</el-button>
          <el-button type="primary" class="button-margin">数据仓库</el-button>
          <el-button type="primary" class="button-margin">全局档案</el-button>
          <el-button type="primary" class="button-margin">布控告警</el-button>
          <el-button type="primary" class="button-margin">社区研判</el-button>
          <el-button type="primary" class="button-margin">系统管理</el-button>
          <!-- ... 其他按钮 ... -->
        </el-col>
      </el-row>
    </el-header>

    <!-- 竖排按钮和地图区域 -->
    <el-main class="main-content-section">
      <el-row type="flex" justify="start" align="middle" class="content-row">
        <!-- 左侧竖排按钮 -->
        <el-col :span="8" class="button-column">
          <el-button>社区地图</el-button>
          <el-button @click="goToSix">一标六实</el-button>
          <el-button>辖区实口</el-button>
          <el-button>辖区车辆</el-button>
          <el-button>视频档案</el-button>
        </el-col>

        <!-- 列表显示区域 -->
        <el-col :span="50" class="custom-list-column">
          <div>
            <el-table :data="tableData" style="width: 500px" show-header="false">
              <el-table-column>
                <template slot-scope="scope">
                  <p><strong>实有人口:</strong> {{ scope.row.populationCount }}</p>
                  <p><strong>实有房屋:</strong> {{ scope.row.buildingCount }}</p>
                  <p><strong>实有单位:</strong> {{ scope.row.buildingCount }}</p>
                  <p><strong>实有车辆:</strong> {{ scope.row.carCount }}</p>
                  <p><strong>实有设备:</strong> {{ scope.row.equipmentCount }}</p>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>

        <!-- 右侧地图和搜索区域 -->
        <el-col :span="16" class="map-and-search-column">
          <div class="search_box" style="width: 1400px">
            关键字搜索：<el-input v-model="input" placeholder="请输入内容" style="width: 250px;padding-right: 20px"  id="tipinput"></el-input>
            经度：<el-input v-model="longitude" placeholder="请输入经度" style="width: 250px;padding-right: 20px" ></el-input>
            纬度：<el-input v-model="latitude" placeholder="请输入纬度" style="width: 250px;padding-right: 20px" ></el-input>
            <button @click="searchMapByCoordinates" style="height: 40px" >根据经纬度查询地图</button>
            <button id="fullscreenBtn" style="width: 80px;padding-left: 20px">全屏</button>
          </div>
          <div ref="gaode_Map" id="gaode_Map" style="width: 1500px; height: 70vh; border: 1px solid #ccc;"></div>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>
<script>

import AMapLoader from "@amap/amap-jsapi-loader";

import {findlist, findOutline, findPloat, findPlotLists} from "@/api/community/plot"; //引入AMapLoader
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "a97ace3a685329a45d528a00b082b51d",
};
export default {
  components: {},
  props: [],
  data() {
    return {
      tableData:[],
      loading: false,
      // visible: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      rules: {},
      input: "",
      input1: "",
      longitude: "",
      latitude: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
      outlineValue:'',
      acc:[],
      point:[],
      // lng: 0, // 初始化经度
      // lat: 0, // 初始化纬度
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getData();
    this.getData1();
    this.initMap();

  },
  mounted() {
    const id = this.$route.query.id;
    // 在这里可以继续处理ID值或者进行其他操作

    // 在这里可以继续处理ID值或者进行其他操作
  },
  methods: {
    goToSix() {
      this.$router.push('/IC/FaceCapture/index/list')
    },
    getData(){
      findPloat(this.$route.query.id).then(res=>{
        this.tableData=res.data
        this.total=res.data.total

      })
    },
    getOutline(){
      findOutline(this.$route.query.id).then(res=>{
        this.outlineValue=res.data
        alert(this.outlineValue)
      })
    },
    getData1(){
      findPlotLists().then(res=>{
        this.tableData1=res.data
        this.addMarkers()
        this.total=res.data.total
        console.log(this.tableData1);
      })
    },
    addMarkers() {
      this.tableData1.forEach((tableData1, index) => {
        let marker = new AMap.Marker({
          position: [tableData1.longitude, tableData1.latitude],
        });
        marker.setMap(this.map);
        this.markers.push(marker);
      });
    },
    // 地图初始化
    initMap() {
      let centerLen = [this.$route.query.longitude, this.$route.query.latitude];
      AMapLoader.load({
        key: "085f7d1a48acc9b9611b99096b0a0589", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder", 'AMap.ToolBar',
          'AMap.Scale'],
      })
        .then((AMap) => {
          this.Amap = AMap;
          this.map = new AMap.Map("gaode_Map", {
            // 设置地图容器id
            viewMode: "3D", //  是否为3D地图模式
            zoom: 18, // 初始化地图级别
            center: centerLen, //中心点坐标
            resizeEnable: true,
          });
          let points = [];
            findOutline(this.$route.query.id).then(res=>{
              this.outlineValue=res.data
              alert(this.outlineValue)
              let coordinatesArray = this.outlineValue.split(',');
              let pointsString = ''; // 用于构建最终的字符串


              let pointsCollection = [];

              for (let i = 0; i < coordinatesArray.length; i += 2) {
                if (i > 0) {
                  pointsString += ', '; // 在坐标点之间添加逗号加空格
                }
                pointsString += `[${coordinatesArray[i]},${coordinatesArray[i + 1]}]`; // 将坐标点用方括号包围
                pointsCollection.push([coordinatesArray[i], coordinatesArray[i + 1]]); // 将坐标点添加到集合中
              }

              let pointsArray = [];
              for (let i = 0; i < coordinatesArray.length; i += 2) {
                pointsArray.push([parseFloat(coordinatesArray[i]), parseFloat(coordinatesArray[i + 1])]);
              }

              console.log(pointsString);
              console.log(pointsCollection); // 输出包含坐标点的集合

              var polygon = new AMap.Polygon({
              map: this.map,
              path: pointsCollection,
              strokeColor: "#FF33FF", // 线颜色
              strokeWeight: 6, // 线宽
              strokeOpacity: 0.2, // 线透明度
              fillColor: '#1791fc', // 填充色
              fillOpacity: 0.35, // 填充透明度
              zIndex: 50,
            });
            })
          this.setMarker(centerLen)
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
          // 添加全屏按钮点击事件
          document.getElementById('fullscreenBtn').addEventListener('click', function () {
            if (this.map.getContainer().requestFullscreen) {
              this.map.getContainer().requestFullscreen();
            } else if (this.map.getContainer().mozRequestFullScreen) { /* Firefox */
              this.map.getContainer().mozRequestFullScreen();
            } else if (this.map.getContainer().webkitRequestFullscreen) { /* Chrome, Safari & Opera */
              this.map.getContainer().webkitRequestFullscreen();
            } else if (this.map.getContainer().msRequestFullscreen) { /* IE/Edge */
              this.map.getContainer().msRequestFullscreen();
            }
          }.bind(this)); // 使用bind确保this指向正确
        })
        .catch((e) => {
        });
      this.getList();

    },
    searchMapByCoordinates() {
      let lng = parseFloat(this.longitude); // 将经度从字符串转换为数值类型
      let lat = parseFloat(this.latitude); // 将纬度从字符串转换为数值类型

      if (isNaN(lng) || isNaN(lat)) {
        alert('请输入有效的经度和纬度');
        return;
      }
      // 根据经度和纬度设置地图中心点
      let map = new AMap.Map("gaode_Map", {
        resizeEnable: true,
        center: [lng, lat],
        zoom: 13
      });

      // 在地图上添加标记点
      // let marker = new AMap.Marker({
      //   position: [lng, lat],
      //   map: map
      // });
      // 创建圆形
      let circle = new this.Amap.Circle({
        center: [lng, lat], // 设置圆心位置
        radius: 1000, // 设置半径，单位为米
        strokeColor: "#FF33FF", // 线颜色
        strokeOpacity: 0.3, // 线透明度
        strokeWeight: 3, // 线宽
        fillColor: "#1791fc", // 填充颜色
        fillOpacity: 0.2, // 填充透明度
      });

      // 将圆形添加到地图上
      circle.setMap(map);
      // 模拟社区数据，实际情况请根据您的数据源获取真实社区数据
      let communities = [
        {name: "Community A", lng: lng + 0.005, lat: lat + 0.005},
        {name: "Community B", lng: lng - 0.003, lat: lat - 0.005},
        {name: "Community C", lng: lng + 0.002, lat: lat - 0.002}
        // Add more communities as needed
      ];

      // 统计圆形区域内的社区总数
      let communityCount = communities.filter(community => {
        return this.calculateDistance(community.lng, community.lat, lng, lat) <= radius;
      }).length;

      console.log("Total community count in the circle: ", communityCount);
      alert("此区域内社区数量为：" + communityCount);
    },

// 计算两点之间的距离
    calculateDistance(lng1, lat1, lng2, lat2) {
      let radian = Math.PI / 180;
      let radius = 6378137; // 地球半径，单位为米
      let dLat = (lat2 - lat1) * radian;
      let dLng = (lng2 - lng1) * radian;
      let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * radian) * Math.cos(lat2 * radian) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
      let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return radius * c;
    },

    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },
    //选中查询出的记录
    selectSite(e) {
      if (e.poi.location) {
        // this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        let geocoder = new AMap.Geocoder({});
        let that = this;
        geocoder.getAddress(this.lnglat, function (status, result) {
          if (status === "complete" && result.regeocode) {
            that.province = result.regeocode.addressComponent.province;
            that.city = result.regeocode.addressComponent.city;
            //自己想要赋的值，根据自己的做修改
            that.$set(that.form, "province", that.province);
            that.$set(that.form, "city", that.city);
            that.$set(that.form, "address", e.poi.name);
            that.$set(
              that.form,
              "coordinate",
              e.poi.location.lng + "," + e.poi.location.lat
            ); //纬度，经度
          } else {
          }
        });
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },

    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler(e) {
      this.dataForm.kqLongitude = e.lnglat.getLng();
      this.dataForm.kqLatitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      alert(this.lnglat);
      this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          that.dataForm.kqLocation = result.regeocode.formattedAddress;
        } else {
        }
      });
      // this.position = {
      //   longitude: e.lnglat.getLng(),
      //   latitude: e.lnglat.getLat(),
      //   address: that.address,
      // };
      // this.input = that.address; //把查询到的地址赋值到输入框
    },
    //  添加标记
    setMarker(lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },

  },
};
</script>


<style lang="scss">

.top-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 20px; /* 减少内边距 */
  background-color: #f0f2f5; /* 背景色，根据需要调整 */
}

.title {
  /* 如果需要，可以在这里调整标题的样式，比如字体大小、行高等 */
  font-size: 20px;
  font-weight: bold;
  /* 设置右边距为0 */
  margin-right: 0;
}

/* ... 其他样式 ... */
.page-container {
  padding: 0;
  box-sizing: border-box;
}


.button-row {
  margin-top: 0; /* 确保没有额外的上边距 */
}

.top-button-row .el-button {
  margin-left: 10px; /* 按钮之间的间距 */
}

.page-container {
  padding: 0;
  margin: 0;
}

.top-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #f5f5f5;
}


.button-column {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px; /* 或者使用 margin-bottom 在每个按钮上 */
}

.map-and-search-column {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.search_box {
  margin-bottom: 10px;
}

.label {
  margin-bottom: 5px;
}

#gaode_Map {
  /* 这里可以添加更多的地图样式，但注意样式应该与地图API的初始化兼容 */
}

.top-section {
  display: flex; /* 使用flex布局使元素并排显示 */
  align-items: center; /* 垂直居中 */
}

.title {
  font-weight: bold; /* 加粗标题 */
  font-size: 18px; /* 增大字体大小 */
  margin-right: 20px; /* 与右侧按钮保持间距 */
}

.button-margin {
  margin-left: 10px; /* 按钮之间的间距，第一个按钮前不需要，所以不在此处设置 */
}


/* 高德地图风格的全屏按钮样式 */
#fullscreenBtn {
  background-color: #1791fc; /* 高德地图常用的蓝色 */
  border: none; /* 移除边框 */
  color: white; /* 白色文字 */
  padding: 8px 16px; /* 适当的内边距 */
  text-align: center; /* 文字居中 */
  font-size: 14px; /* 字体大小，高德地图的按钮文字通常较小 */
  cursor: pointer; /* 鼠标悬停时显示指针 */
  border-radius: 4px; /* 圆角，高德地图的按钮圆角通常较小 */
  transition: background-color 0.3s, transform 0.3s; /* 平滑过渡效果，包括背景色和可能的变换（如缩放） */
  outline: none; /* 移除点击时的轮廓线 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加一些阴影效果，增强立体感 */
  /* 可选：添加图标，这里用伪元素模拟一个简单的图标 */
  position: relative;
  padding-left: 30px; /* 为图标留出空间 */
}


/* 鼠标悬停时的样式变化 */
#fullscreenBtn:hover {
  background-color: #007bff; /* 稍微深一点的蓝色 */
  transform: scale(1.05); /* 轻微放大效果，增强点击反馈 */
}

.search_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;

  .label {
    color: #000;
    width: 100px;
  }
}

.content {
  position: relative;
}

#panel {
  position: absolute;
  top: 50px;
  right: 20px;
}

#gaode_Map {
  overflow: hidden;
  width: 100%;
  height: 540px;
  margin: 0;
}

.amap-sug-result {
  z-index: 2999 !important;
}
</style>



